import json
from django.http import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection
from ihome.libs.captcha.captcha import captcha
import random
# from meiduo_mall.libs.yuntongxun.ccp_sms import CCP

import logging
logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request):

        text, image = captcha.generate_captcha()
        cur = request.GET.get('cur')

        redis_conn = get_redis_connection('verify_code')
        redis_conn.set('img_%s' % cur, text, 300)

        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):

    def post(self, request):

        req_data = json.loads(request.body.decode())
        mobile = req_data.get('mobile')
        id = req_data.get('id')
        text = req_data.get('text')

        if not all([mobile, id, text]):
            return JsonResponse({"errno": 400,
                                 "errmsg": "缺少必传参数"})

        redis_conn = get_redis_connection('verify_code')

        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:

            return JsonResponse({"errno": 400,
                                 "errmsg": "短信发送过于频繁!"})

        image_code_redis = redis_conn.get('img_%s' % id)

        if image_code_redis is None:
            return JsonResponse({"errno": 400,
                                 "errmsg": "缺少必传参数"})

        try:
            redis_conn.delete('img_%s' % id)
        except Exception as e:
            logger.error(e)

        if text.lower() != image_code_redis.lower():
            return JsonResponse({"errno": 400,
                                 "errmsg": "输入图形验证码有误"})

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info('短信验证码为：%s' % sms_code)

        try:

            pl = redis_conn.pipeline()

            pl.set('sms_%s' % mobile, sms_code, 300)

            pl.set('send_flag_%s' % mobile, 1, 60)


            pl.execute()
        except Exception as e:
            return JsonResponse({"errno": 400,
                                 "errmsg": "保存短信验证码出错"})

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        return JsonResponse({"errno": 0,
                             "errmsg": "发送成功"})